package com.shensi.adminCollect.controller.coupon;

import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.coupon.CouponInfo;
import com.shensi.adminCollect.service.coupon.ICouponInfoService;
import com.shensi.adminCollect.domain.system.SysEnterpriseUser;
import com.shensi.adminCollect.domain.system.SysStationUser;
import com.shensi.adminCollect.service.system.ISysEnterpriseUserService;
import com.shensi.adminCollect.service.system.ISysStationUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 优惠劵Controller
 *
 * @author qujia
 * @date 2021-08-09
 */
@Api(tags = "优惠券info")
@RestController
@RequestMapping("/coupon/info")
public class CouponInfoController extends BaseController
{
    @Autowired
    private ICouponInfoService couponInfoService;


    @Autowired
    private ISysEnterpriseUserService sysEnterpriseUserService;
    @Autowired
    private ISysStationUserService sysStationUserService;

    /**
     * 查询优惠劵列表
     */
    @ApiOperation("查询优惠卷信息")
    @ApiImplicitParam(name = "list", value = "查询优惠卷信息list", dataType = "CouponInfo")
    @GetMapping("/list")
    public TableDataInfo list(CouponInfo couponInfo,String date)
    {
       LoginUser current= SecurityUtils.getLoginUser();
       if("0".equals(current.getUser().getUserLevel())){
           return getDataTable(Collections.emptyList());
       }else {
           couponInfo.setEnterpriseId(current.getUser().getEnterpriseId());
       }

        startPage();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CouponInfo> list;
//        if (Objects.nonNull(date)){
//           list =couponInfoService.selectCoupon(date);
//        }else {
            list = couponInfoService.selectCouponInfoList(couponInfo);
//        }
        if(list!=null && list.size()>0){
            for(CouponInfo coupon:list){

                List<String> eff = new ArrayList<>();
                if(coupon!=null && coupon.getEffectiveTimeStart()!=null){
                    eff.add(dateFormat.format(coupon.getEffectiveTimeStart()));
                }
                if(coupon!=null && coupon.getEffectiveTimeEnd()!=null){
                    eff.add(dateFormat.format(coupon.getEffectiveTimeEnd()));
                }
                coupon.setEffectiveTime(eff);
                if(coupon!=null && coupon.getAppointedDays()!=null){
                    coupon.setAppointedDaysList(Arrays.asList(coupon.getAppointedDays().split(",")));
                }
                if(coupon!=null && coupon.getCycleDays()!=null){
                    coupon.setCycleDaysList(Arrays.asList(coupon.getCycleDays().split(",")));
                }
                if(coupon!=null && coupon.getVerification()!=null){
                    List<Integer> idlist=new ArrayList<>();
                    List<String> namelist=new ArrayList<>();
                   String ids[]=  coupon.getVerification().split(",");
                   for(String id:ids){
                       idlist.add(Integer.parseInt(id));
                       SysStationUser sysStation=sysStationUserService.selectSysStationUserById(Long.parseLong(id));
                       if(sysStation!=null){
                           namelist.add(sysStation.getStationName());
                       }else {
                           namelist.add("");
                       }
                   }
                    coupon.setVerificationList(idlist);
                    coupon.setVerificationNameList(namelist);
                }

            }
        }
        return getDataTable(list);
    }
    /**
     * 查询优惠卷启用状态
     */
    @GetMapping("/selectCouponEnableFalge")
    public AjaxResult selectCouponEnableFalge()
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysEnterpriseUser sysEnterpriseUser=sysEnterpriseUserService.selectSysEnterpriseUserById(currentUser.getUser().getEnterpriseId());
        if(sysEnterpriseUser==null){
            return AjaxResult.error("没有操作权限");
        }
        if(sysEnterpriseUser.getCouponEnabledFlag()==null){
            return AjaxResult.success(0);
        }
        return AjaxResult.success(Integer.parseInt(sysEnterpriseUser.getCouponEnabledFlag()));
    }

    /**
     * 导出优惠劵列表
     */
    @GetMapping("/export")
    public AjaxResult export(CouponInfo couponInfo)
    {
        List<CouponInfo> list = couponInfoService.selectCouponInfoList(couponInfo);
        ExcelUtil<CouponInfo> util = new ExcelUtil<CouponInfo>(CouponInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 获取优惠劵详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CouponInfo couponInfo = couponInfoService.selectCouponInfoById(id);

        List<String> eff = new ArrayList<>();
        if(couponInfo!=null && couponInfo.getEffectiveTimeStart()!=null){
            eff.add(dateFormat.format(couponInfo.getEffectiveTimeStart()));
        }
        if(couponInfo!=null && couponInfo.getEffectiveTimeEnd()!=null){
            eff.add(dateFormat.format(couponInfo.getEffectiveTimeEnd()));
        }
        couponInfo.setEffectiveTime(eff);

        if(couponInfo!=null && couponInfo.getAppointedDays()!=null){
            couponInfo.setAppointedDaysList(Arrays.asList(couponInfo.getAppointedDays().split(",")));
        }
        if(couponInfo!=null && couponInfo.getCycleDays()!=null){
            couponInfo.setCycleDaysList(Arrays.asList(couponInfo.getCycleDays().split(",")));
        }
        if(couponInfo!=null && couponInfo.getVerification()!=null){
            List<Integer> idlist=new ArrayList<>();
            List<String> namelist=new ArrayList<>();
            String ids[]=  couponInfo.getVerification().split(",");
            for(String sid:ids){
                idlist.add(Integer.parseInt(sid));
                SysStationUser sysStation=sysStationUserService.selectSysStationUserById(Long.parseLong(sid));
                if(sysStation!=null){
                    namelist.add(sysStation.getStationName());
                }else {
                    namelist.add("");
                }
            }
        }
        return AjaxResult.success(couponInfo);
    }

    /**
     * 新增优惠劵
     */
    @PostMapping
    public AjaxResult add(@RequestBody CouponInfo couponInfo)
    {

        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            LoginUser currentUser = SecurityUtils.getLoginUser();
            if(!"1".equals(currentUser.getUser().getUserLevel())){
                return AjaxResult.error("权限不足");
            }
            couponInfo.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            couponInfo.setCreateBy(String.valueOf(currentUser.getUser().getUserId()));
            if(couponInfo!=null && couponInfo.getEffectiveTime() !=null&& couponInfo.getEffectiveTime().size()>0){
                String start = couponInfo.getEffectiveTime().get(0);
                String end = couponInfo.getEffectiveTime().get(1);
                if(start!=null && start!=""){
                    couponInfo.setEffectiveTimeStart( dateFormat.parse(start));
                }
                if(end!=null && end!=""){
                    couponInfo.setEffectiveTimeEnd(dateFormat.parse(end));
                }
            }
            if(couponInfo!=null&& couponInfo.getCycleDaysList() !=null && couponInfo.getCycleDaysList().size()>0){
                String cycleDays= String.join(",", couponInfo.getCycleDaysList());
                couponInfo.setCycleDays(cycleDays);
            }
            if(couponInfo!=null&& couponInfo.getAppointedDaysList() !=null && couponInfo.getAppointedDaysList().size()>0){
                String appointedDays= String.join(",", couponInfo.getAppointedDaysList());
                couponInfo.setAppointedDays(appointedDays);
            }
            if(couponInfo!=null&& couponInfo.getVerificationList() !=null && couponInfo.getVerificationList().size()>0){
                String verification= StringUtils.join( couponInfo.getVerificationList(),",");
                couponInfo.setVerification(verification);
            }
            if(couponInfo!=null&& couponInfo.getEffectiveTimeType() !=null &&couponInfo.getEffectiveTimeType().equals("1") ){
               if(couponInfo.getEffectiveTimeEnd().before(couponInfo.getEffectiveTimeStart())){
                   return AjaxResult.error("截止时间不得小于开始时间");
               }
                if(couponInfo.getEffectiveTimeEnd().before(new Date())){
                    return AjaxResult.error("当前优惠卷的截止时间已经超期");
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return toAjax(couponInfoService.insertCouponInfo(couponInfo));
    }

    /**
     * 修改优惠劵
     */
    @PutMapping
    public AjaxResult edit(@RequestBody CouponInfo couponInfo)
    {
        try {

            if(couponInfo!=null && couponInfo.getEffectiveTime() !=null&& couponInfo.getEffectiveTime().size()>0){
                String start = couponInfo.getEffectiveTime().get(0);
                String end = couponInfo.getEffectiveTime().get(1);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(start!=null && start!=""){
                    couponInfo.setEffectiveTimeStart( dateFormat.parse(start));
                }
                if(end!=null && end!=""){
                    couponInfo.setEffectiveTimeStart(dateFormat.parse(end));
                }
            }

            if(couponInfo!=null&& couponInfo.getCycleDaysList() !=null && couponInfo.getCycleDaysList().size()>0){
                String cycleDays= String.join(",", couponInfo.getCycleDaysList());
                couponInfo.setCycleDays(cycleDays);
            }
            if(couponInfo!=null&& couponInfo.getAppointedDaysList() !=null && couponInfo.getAppointedDaysList().size()>0){
                String appointedDays= String.join(",", couponInfo.getAppointedDaysList());
                couponInfo.setAppointedDays(appointedDays);
            }
            if(couponInfo!=null&& couponInfo.getVerificationList() !=null && couponInfo.getVerificationList().size()>0){
                String verification= StringUtils.join( couponInfo.getVerificationList(),",");
                couponInfo.setVerification(verification);
            }
            if(couponInfo.getEditFlag()=="1"){
               return toAjax(0) ;
            };
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return toAjax(couponInfoService.updateCouponInfo(couponInfo));
    }

    /**
     * 删除优惠劵
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(couponInfoService.deleteCouponInfoByIds(ids));
    }
}
